<template>
  <ContentWrap>
    <div class="btn-all">
      <el-button type="primary" @click="onAdd()"
        ><Icon icon="material-symbols:add" color="white" />&nbsp;{{
          t('dataDictionary.add')
        }}</el-button
      >
      <el-button @click="exportXls" type="primary"
        ><Icon icon="uil:import" color="white" />&nbsp;{{ t('dataDictionary.export') }}</el-button
      >
      <!-- <el-button @click="importData" type="primary"
        ><Icon icon="mdi:export" color="white" />&nbsp;{{ t('dataDictionary.import') }}</el-button
      > -->
      <el-upload
        class="upload-demo"
        :http-request="importData"
        :show-file-list="false"
        accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      >
        <el-button type="primary"
          ><Icon icon="mdi:export" color="white" />&nbsp;{{ t('dataDictionary.import') }}</el-button
        >
      </el-upload>
      <el-select v-if="count > 0" @change="changeDelete" placeholder="批量操作">
        <el-option label="" value="1"
          ><Icon icon="material-symbols:delete-outline" color="#606266" /><span
            >删除</span
          ></el-option
        >
      </el-select>
    </div>
    <div class="choose-box mb-20px">
      <p>
        {{ t('dataLog.selected') }} <i> {{ count }} </i> {{ t('dataLog.sum') }}
        <span @click="onEmpty"> {{ t('dataLog.empty') }} </span>
      </p>
    </div> 
    <el-table
      v-if="tableStatus"
      ref="multipleTableRef"
      :data="tableData1"
      style="width: 100%"
      row-key="id"
      @selection-change="handleSelectionChange"
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChild' }"
    >
      <el-table-column type="selection" width="55" :reserve-selection="true" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="code" label="分类编码" />
      <el-table-column prop="sort" label="排序" />
      <el-table-column label="操作">
        <template #default="scope">
          <div class="btn-content">
            <span @click="onEdit(scope.$index, scope.row)" class="oper-btn">{{
              t('dataDictionary.edit')
            }}</span>
            <i class="line"></i>
            <el-popover :visible="scope.row.visibleStatus" placement="top" :width="160">
              <p>确定删除吗?</p>
              <div style="text-align: right; margin: 0">
                <el-button size="small" text @click="scope.row.visibleStatus = false"
                  >取消</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="confirmDelete(scope.$index, scope.row)"
                  >确定</el-button
                >
              </div>
              <template #reference>
                <span @click="handleDelete(scope.$index, scope.row)" class="oper-btn">
                  {{ t('formDemo.delete') }}</span
                >
              </template>
            </el-popover>
            <i class="line"></i>
            <span class="oper-btn" @click="onSet(scope.row)">添加下级</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination
        v-show="tableData1.length > 0"
        v-model:current-page="currentPage4"
        v-model:page-size="pageSize4"
        :page-sizes="[10, 20, 30, 40]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <DiaForm ref="diaForm" @submit="onSubmit" />
    <el-dialog v-model="centerDialogVisible" title="确认删除？" width="30%" align-center>
      <span>是否删除选中数据?</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDeleteBatch"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, provide } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage, ElTable, ElMessageBox } from 'element-plus'
import DiaForm from './components/form.vue'
import { classListType, classChildListType, User } from './type'
import { uploadExcelApi, dictExportXlsAll, downXls } from '@/api/common/import'
import {
  getClassList,
  getClassChildList,
  categoryRemoveId,
  categoryDeleteBatch
} from '@/api/classDictionary/index'
const { t } = useI18n()
const count = ref(0)
const tableStatus = ref(false)
const centerDialogVisible = ref(false)
//渲染数据
const classListData = ref<classListType>({
  _t: '1680599158',
  column: 'createTime',
  order: 'desc',
  field: 'id,,name,code,action',
  pageNo: 1,
  pageSize: 10
})
//渲染子级
const classChildListData = ref<classChildListType>({
  _t: '1680599158',
  column: 'createTime',
  order: 'desc',
  field: 'id,,name,code,action',
  pageNo: 1,
  pageSize: 10,
  pid: 0
})
const tableData1 = ref<User[]>([])
const multipleSelection = ref<User[]>([])
const handleSelectionChange = (val: User[]) => {
  // console.log(val, 'val')
  multipleSelection.value = val
  count.value = multipleSelection.value.length
}
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const onEmpty = () => {
  count.value = 0
  multipleTableRef.value!.clearSelection()
}
const deleteData = reactive({ id: '' })
// 分页
const currentPage4 = ref(4)
const pageSize4 = ref(10)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const total = ref(1)
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`)
}
const pageData = () => {}

// 新增弹框
let diaForm = ref<InstanceType<typeof DiaForm> | null>(null)
const onAdd = () => {
  diaForm.value?.dialogOnAdd(true)
}
// 编辑
let onEdit = (index, row) => {
  diaForm.value?.dialogOnEdit(true, row)
}
//添加子级
let onSet = (row) => {
  row.hasChild = "0"
  diaForm.value?.dialogChildOnAdd(true, row)
}
//监听子组件传递事件
const onSubmit = (payload) => {
  payload ? getClassListFn() : ''
}

//懒加载
const load = async (row: User, treeNode: unknown, resolve: (date: User[]) => void) => {
  // console.log(treeNode, 'treeNode', multipleSelection.value)
  classChildListData.value.pid = row.id
  let { result } = await getClassChildList(classChildListData.value)
  //
  // let chooseData = multipleSelection.value
  // setTimeout(() => {
  // }, 1000)
  resolve(result)
  await setNewRowData(row, result)
}
const setNewRowData = (row, loadData) => {
  row.children = loadData
}
// 删除弹窗
let handleDelete = (ind, row) => {
  // 清空一下其他打开的气泡框
  tableData1.value.map((item: any) => {
    item.visibleStatus = false
  })
  row.visibleStatus = true
  deleteData.id = row.id
}
//删除单个id确定
const confirmDelete = async () => {
  let { code, message } = await categoryRemoveId({ id: deleteData.id })
  if (Number(code) == 200) {
    getClassListFn()
    ElMessage({
      message: message,
      type: 'success'
    })
  } else {
    ElMessage.error(message)
  }
}
//批量删除选择
const changeDelete = async (val: string) => {
  // console.log(multipleSelection.value)
  centerDialogVisible.value = true
}
//批量删除确定
const confirmDeleteBatch = async () => {
  let arr: object[] = []
  multipleSelection.value.map((item: any) => {
    arr.push(item.id)
  })
  let { code, message } = await categoryDeleteBatch({ ids: arr.join(',') })
  if (Number(code) == 200) {
    getClassListFn()
    ElMessage({
      message: message,
      type: 'success'
    })
    count.value = 0
    centerDialogVisible.value = false
  } else {
    ElMessage.error(message)
  }
}
//获取列表
let getClassListFn = async () => {
  tableStatus.value = false
  let { result } = await getClassList(classListData.value)
  currentPage4.value = result.current
  pageSize4.value = result.size
  total.value = result.total
  result.records.map((item) => {
    item.visibleStatus = false
    if (item.hasChild == '1') {
      item.hasChildren = true
    } else {
      item.hasChildren = false
    }
  })
  tableData1.value = result.records

  tableStatus.value = true
}
//导出
const exportXls = async () => {
  let result = await dictExportXlsAll('/sys/category/exportXls', 'post', '', 'blob')
  // console.log(result)
  if (result.status == '200') {
    downXls(result, '分类字典', '')
    ElMessage({
      message: result.statusText,
      type: 'success'
    })
  } else {
    ElMessage.error(result.statusText)
  }
}
// 导入
const importData = async ({ file }) => {
  let rst = await uploadExcelApi(file, '/sys/category/importExcel')
  let { data } = rst
  if (data.code == 200 && data.success) {
    ElMessage.success('文件上传成功')
    getClassListFn()
  } else {
    ElMessage.error(`文件上传失败，${data.message}`)
  }
}
onMounted(() => {
  getClassListFn()
})
</script>

<style lang="less" scoped>
@import './index.less';
</style>
